import React, { Component } from "react";



export default class Son extends Component {
  
  constructor(props){
    super(props);
    console.log("constructor");
    this.state = {
      age:20,
      name:"",
      sex:""
    }
  }

  // 组件应该更新吗？
  shouldComponentUpdate(nextProps, nextState){
    console.log("shouldComponentUpdate");
    // console.log("this.props",this.props);
    // console.log("nextProps",nextProps);
    // console.log("this.state",this.state);
    // console.log("nextState",nextState);
    
    if(this.compareObj(this.state,nextState) && this.compareObj(this.props,nextProps)){
      return false;//不更新组件。
    }

    return true;
  }

  compareObj(obj1,obj2){

    if(typeof obj1 != "object" || typeof obj2 != "object"){
      return obj1===obj2;
    }
    
    if(Object.keys(obj1).length !== Object.keys(obj2).length){
      return false;
    }

    // 代码能执行到这一行，说明：obj1和Obj2都是对象，而且地址不一样，而且键的数量一样。

    for(let key in obj1){
      if(typeof obj1[key] == "object" && typeof obj2[key] == "object"){
        
        if(!this.compareObj(obj1[key],obj2[key])){
          return false;
        }

      }else{
        
        if(obj1[key]!==obj2[key]){
          return false;
        }

      }
    }

    return true;

  }

  changeAge=()=>{
    this.setState({})
  }

  render() {
    console.log("render");
    return (
      <div>
        <h1>子组件</h1>
        <p>年龄：{this.state.age}</p>
        <input type="button" value="修改年龄" onClick={this.changeAge} />
        <p>this.props.weight：{this.props.weight}</p>
      </div>
    );
  }
}


